import { Authorization } from '@/constants/authorization';
import { ResponseType } from '@/interfaces/database/base';
import i18n from '@/locales/config';
import {
  getAuthorization,
  
} from '@/utils/authorization-util';
import { message } from 'antd';
import { RequestMethod, extend } from 'umi-request';
// import { convertTheKeysOfTheObjectToSnake } from './common-util';

// const FAILED_TO_FETCH = 'Failed to fetch';

const RetcodeMessage = {
  200: i18n.t('message.200'),
  201: i18n.t('message.201'),
  202: i18n.t('message.202'),
  204: i18n.t('message.204'),
  400: i18n.t('message.400'),
  401: i18n.t('message.401'),
  403: i18n.t('message.403'),
  404: i18n.t('message.404'),
  406: i18n.t('message.406'),
  410: i18n.t('message.410'),
  413: i18n.t('message.413'),
  422: i18n.t('message.422'),
  500: i18n.t('message.500'),
  502: i18n.t('message.502'),
  503: i18n.t('message.503'),
  504: i18n.t('message.504'),
};
type ResultCode =
  | 200
  | 201
  | 202
  | 204
  | 400
  | 401
  | 403
  | 404
  | 406
  | 410
  | 413
  | 422
  | 500
  | 502
  | 503
  | 504;

// const errorHandler = (error: {
//   response: Response;
//   message: string;
// }): Response => {
//   const { response } = error;
//   if (error.message === FAILED_TO_FETCH) {
//     notification.error({
//       description: i18n.t('message.networkAnomalyDescription'),
//       message: i18n.t('message.networkAnomaly'),
//     });
//   } else {
//     if (response && response.status) {
//       const errorText =
//         RetcodeMessage[response.status as ResultCode] || response.statusText;
//       const { status, url } = response;
//       notification.error({
//         message: `${i18n.t('message.requestError')} ${status}: ${url}`,
//         description: errorText,
//       });
//     }
//   }
//   return response ?? { data: { code: 1999 } };
// };

const request: RequestMethod = extend({
  timeout: 300000,
  getResponse: true,
});

request.interceptors.request.use((url: string, options: any) => {
  // const data = convertTheKeysOfTheObjectToSnake(options.data);
  // const params = convertTheKeysOfTheObjectToSnake(options.params);
  const data = options.data;
  const params = options.params;
  // 使用getAuthorization()获取正确格式的Bearer token
  const authorization = getAuthorization();

  console.log('参数：：：：')

  return {
    url,
    options: {
      ...options,
      data,
      params,
      headers: {
        ...(options.skipToken
          ? undefined
          : { [Authorization]: authorization }), // 使用正确格式的authorization值
        ...options.headers,
      },
      interceptors: true,
    },
  };
});

request.interceptors.response.use(async (response: Response, options) => {
  console.log('chat-server响应拦截器 - response>>>>', response);
  
  if (response?.status === 413 || response?.status === 504) {
    message.error(RetcodeMessage[response?.status as ResultCode]);
    return response;
  }

  if (options.responseType === 'blob') {
    return response;
  }

  try {
    // 获取响应文本
    const responseText = await response?.clone()?.text();
    console.log('chat-server响应拦截器 - responseText>>>>', responseText);
    
    // 处理流式响应逻辑
    let data: ResponseType = { code: 1999, message: '未解析到数据', data: null };
    
    if (responseText) {
      // 检查是否是流式响应（包含多个JSON对象）
      if (responseText.includes('}\n{') || responseText.includes('}{')) {
        console.log('检测到流式响应格式');
        
        // 分割流式响应的JSON对象
        let jsonStrings: string[] = [];
        
        // 处理换行分隔的情况
        if (responseText.includes('}\n{')) {
          jsonStrings = responseText.split('\n').filter(line => line.trim());
        } 
        // 处理直接连接的情况
        else if (responseText.includes('}{')) {
          // 使用更精确的正则表达式分割
          const regex = /(\{(?:[^{}]|{[^{}]*})*\})/g;
          const matches = responseText.match(regex);
          if (matches) {
            jsonStrings = matches;
          }
        }
        
        console.log('分割后的JSON字符串数量:', jsonStrings.length);
        console.log('最后一个JSON字符串:', jsonStrings[jsonStrings.length - 1]);
        
        // 取最后一个JSON对象（最完整的回答）
        if (jsonStrings.length > 0) {
          const lastJsonString = jsonStrings[jsonStrings.length - 1];
          try {
            const parsed = JSON.parse(lastJsonString);
            console.log('解析最后一个JSON对象成功:', parsed);
            data = parsed;
          } catch (parseError) {
            console.warn('解析最后一个JSON失败，尝试解析倒数第二个:', parseError);
            // 如果最后一个解析失败，尝试倒数第二个
            if (jsonStrings.length > 1) {
              try {
                const secondLastJsonString = jsonStrings[jsonStrings.length - 2];
                const parsed = JSON.parse(secondLastJsonString);
                console.log('解析倒数第二个JSON对象成功:', parsed);
                data = parsed;
              } catch (secondParseError) {
                console.error('解析倒数第二个JSON也失败:', secondParseError);
              }
            }
          }
        }
      } else {
        // 单个JSON对象
        try {
          data = JSON.parse(responseText);
          console.log('解析单个JSON成功:', data);
        } catch (parseError) {
          console.error('解析单个JSON失败:', parseError);
        }
      }
    }

    console.log('chat-server响应拦截器 - 最终data>>>>', data);
    
    // 创建新的响应对象
    const modifiedResponse = Object.create(response);
    modifiedResponse.data = data;
    
    return modifiedResponse;
    
  } catch (error) {
    console.error('chat-server响应拦截器处理失败:', error);
    return response;
  }
});

export default request;

export const get = (url: string) => {
  return request.get(url);
};

export const post = (url: string, body: any) => {
  return request.post(url, { data: body });
};

export const drop = () => {};

export const put = () => {};

// 测试函数：解析包含多个JSON对象的字符串
export const parseMultiJsonString = (responseText: string) => {
  console.log('开始解析多JSON字符串:', responseText);
  
  try {
    // 尝试解析包含多个JSON对象的字符串
    if (responseText && responseText.includes('}{')) {
      // 分割多个JSON对象
      const jsonObjects = responseText.split('}{').map((item, index, array) => {
        if (index === 0) return item + '}';
        if (index === array.length - 1) return '{' + item;
        return '{' + item + '}';
      });
      
      console.log('分割后的JSON对象:', jsonObjects);
      
      // 解析每个JSON对象，寻找包含Result的对象
      let resultData = null;
      for (const jsonStr of jsonObjects) {
        try {
          const parsed = JSON.parse(jsonStr);
          console.log('解析的对象:', parsed);
          if (parsed.Result) {
            resultData = parsed.Result;
            console.log('找到Result数据:', resultData);
            break;
          }
          // 也检查是否直接包含我们需要的数据结构
          if (parsed.code !== undefined || parsed.data !== undefined) {
            resultData = parsed;
            console.log('找到包含code/data的对象:', resultData);
            break;
          }
        } catch (parseError) {
          console.warn('解析JSON对象失败:', parseError, jsonStr);
        }
      }
      
      return resultData;
    } else {
      // 单个JSON对象的情况
      return JSON.parse(responseText);
    }
  } catch (error) {
    console.error('解析响应数据失败:', error, responseText);
    return { code: 1999, message: '数据解析失败', data: null };
  }
};



